const Service = require('egg').Service;
var images = require("images");
const path = require("path")
const fs = require("fs")
const mimeType = require("mime-types")
var request = require('request');
var iconv = require('iconv-lite');
class UtilService extends Service {
    // 读取图片文件转换为 base64 编码
    async imgToBase64(file) {
        try {
            let filePath = path.resolve(file); // 原始文件地址
            let fileMimeType = mimeType.lookup(filePath); // 获取文件的 memeType
            if (!fileMimeType.toString().includes('image')) {
                console.log(chalk.red(`Failed! ${filePath}:\tNot image file!`));
                return;
            }
            // 读取文件数据
            let data = fs.readFileSync(filePath);
            data = Buffer.from(data, 'binary').toString('base64'); // base64编码
            let base64 = 'data:' + fileMimeType + ';base64,' + data;
            console.log('生成成功了')
            return base64
        } catch (err) {
            console.log("出错了")
            return false
        }
    }

    // 压缩图片
    zipImage(srcPath, distPath) {
        images(srcPath)
            .size(1000)
            .save(distPath, {
                quality: 75
            });
    }

    sleep(time = 0) {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve()
            }, time)
        })
    }

    // 获取网页源代码
    httpReq(url, method, encoding, callback) {
        var Cookie = this.ctx.app.config.Cookie
        var userAgent = this.ctx.app.config.userAgent
        request({
            url: url,
            method: method,
            encoding: null,
            headers: {
                "Cookie": Cookie,
                'User-Agent': userAgent
            }
        }, function (err, res, body) {
            body = iconv.decode(body, encoding);
            if (err) {
                console.log(err);
            } else {
                callback(body);
            }
        })
    }


}

module.exports = UtilService;
